package com.qiu.greened.ui.post

import android.util.Log
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import androidx.paging.Pager
import androidx.paging.PagingConfig
import androidx.paging.PagingData
import androidx.paging.cachedIn
import com.qiu.greened.bean.PostBean
import com.qiu.greened.bean.ReplyBean
import com.qiu.greened.data.PostHotPagingSource
import com.qiu.greened.data.ReplyPagingSource
import com.qiu.greened.network.PostService
import com.qiu.greened.network.ServiceCreator
import com.qiu.greened.utils.MyData
import com.qiu.greened.utils.showToast
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.launch

class PostInfoViewModel : ViewModel() {

    private val postService by lazy {
        ServiceCreator.create<PostService>()
    }

    private val _post = MutableLiveData<PostBean>().apply {

    }
    val post: LiveData<PostBean> = _post

    fun loadPost(postId: Int) {
        viewModelScope.launch {
            try {
                val data = ServiceCreator.create<PostService>()
                    .getPost(MyData.token, postId, MyData.userId).dataConvert()
                _post.value = data
            } catch (e: Exception) {
                e.printStackTrace()
                "${e.message}".showToast()
                Log.i("请求失败", "${e.message}")
            }
        }
    }

    /**
     * 获取评论数据
     * cachedIn() 将服务器返回的数据在 viewModelScope 这个作用域内进行缓存
     */
    fun getPagingData(postId: Int): Flow<PagingData<ReplyBean>> {
        return Pager(PagingConfig(pageSize = 10)) {
            ReplyPagingSource(postService, postId)
        }.flow.cachedIn(viewModelScope)
    }
}